<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="filter-container">
      <el-row :gutter="0">
        <el-form :inline="true" class="search-form">
          <el-form-item label="名称">
            <el-input v-model="query.name" class="filter-item" placeholder="请输入名称" clearable/>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="query.email" class="filter-item" placeholder="请输入邮箱" clearable/>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="query.range_date"
              type="daterange"
              class="filter-item"
              style="width: 240px;"
              range-separator="-"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button class="" type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button class="" type="success" icon="el-icon-refresh-right" plain @click="refresh()">刷新</el-button>
          </el-form-item>

          <el-form-item style="float: right">
            <el-button class="" type="primary" @click="add()">添加</el-button>
          </el-form-item>
        </el-form>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table ref="tableRef" v-loading="loading" :data="datas" :max-height="height" style="width: 100%" border @sort-change="sorting">
      <el-table-column prop="id" label="ID" min-width="60" align="center" sortable="custom"/>
      <el-table-column prop="avatar" label="头像" min-width="70" align="center">
        <template slot-scope="scope">
          <el-image v-if="scope.row.full_avatar" :src="scope.row.full_avatar" :preview-src-list="[scope.row.full_avatar]"/>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="账号" min-width="120" align="center" show-overflow-tooltip/>
      <el-table-column prop="nickname" label="昵称" min-width="120" align="center" show-overflow-tooltip/>
      <el-table-column prop="email" label="邮箱" min-width="160" align="center" show-overflow-tooltip/>
      <el-table-column prop="role_names" label="角色" min-width="160" align="center" show-overflow-tooltip/>
      <el-table-column prop="sorting" label="排序" min-width="75" align="center" sortable="custom"/>
      <el-table-column prop="status" label="启用" min-width="75" align="center" sortable="custom">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="isActivate(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" min-width="160" align="center" sortable="custom"/>
      <el-table-column label="操作" min-width="220" align="center" fixed="right">
        <template slot-scope="{ row }">
          <el-button type="warning" icon="el-icon-key" size="mini" @click="setPwd(row)">密码</el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(row)">编辑</el-button>
          <el-button v-if="row.type != '0'" type="danger" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="query.page" :limit.sync="query.limit" @pagination="list"/>

    <!-- 添加、修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" top="10vh" width="50%" :close-on-click-modal="false" :before-close="cancel">
      <el-form ref="formRef" :model="model" :rules="rules" label-width="100px" class="">
        <el-form-item label="头像" prop="full_avatar">
          <single-upload :single-file="model.single_file" :show-file-list="false" accept="image/jpeg, image/png, image/gif" @uploadCallback="singleCallback"/>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="model.username" placeholder="请输入账号" clearable/>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="model.nickname" placeholder="请输入昵称" clearable/>
        </el-form-item>
        <el-form-item v-if="model.id == ''" label="密码" prop="password">
          <el-input v-model="model.password" placeholder="请输入密码" show-password clearable/>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="model.phone" clearable/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="model.email" clearable/>
        </el-form-item>
        <el-form-item label="排序" prop="sorting">
          <el-input-number v-model="model.sorting" :min="1" :max="99999" step-strictly controls-position="right"/>
        </el-form-item>
        <el-form-item label="角色" prop="role_ids">
          <el-checkbox v-model="model.role_ids" v-for="(role, index) in roleList" :key="index" :label="role.id">{{ role.name }}</el-checkbox>
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="model.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item v-if="model.id" label="最后登录IP" prop="last_login_ip">
          <el-col :span="10">
            <el-input v-model="model.last_login_ip" disabled/>
          </el-col>
          <el-col class="line" :span="4" style="text-align:center">最后登录时间</el-col>
          <el-col :span="10">
            <el-input v-model="model.last_login_time" disabled/>
          </el-col>
        </el-form-item>
        <el-form-item v-if="model.id" label="创建时间" prop="created_at">
          <el-col :span="10">
            <el-input v-model="model.created_at" disabled/>
          </el-col>
          <el-col class="line" :span="4" style="text-align:center">更新时间</el-col>
          <el-col :span="10">
            <el-input v-model="model.updated_at" disabled/>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="submit">提交</el-button>
      </div>
    </el-dialog>
    <!-- 重置密码 -->
    <el-dialog :title="'设置密码：'+model.id" :visible.sync="pwdDialog" width="30%" :close-on-click-modal="false">
      <el-form ref="pwdRef" :rules="pwdRules" :model="model" label-width="100px">
        <el-form-item label="账号">
          <el-input v-model="model.username" clearable disabled/>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="model.nickname" clearable disabled/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="model.password" placeholder="请输入新密码" show-password clearable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setPwdCancel">取消</el-button>
        <el-button :loading="pwdBtnLoading" type="primary" @click="setPwdSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination'
import SingleUpload from '@/components/FileUpload'
import {list as roleList} from '@/api/admin/role'
import {list, info, save, del, setPwd, disable, checkName} from '@/api/admin/admin'

export default {
  name: 'AdminAdmin',
  components: {Pagination, SingleUpload},
  data() {
    const roleValidate = (rule, value, callback) => {
      if (value.length < 2) {
        this.$message({
          message: '请至少选择一个角色',
          type: 'info'
        })
        callback(new Error('角色为必传项'))
      } else {
        callback()
      }
    }
    return {
      height: 680,
      loading: false,
      datas: [],
      total: 0,
      query: {
        page: 1,
        limit: 20,
        name: '',
        email: '',
        range_dates: []
      },
      dialogVisible: false,
      dialogTitle: '',
      btnLoading: false,
      model: {
        id: '',
        created_at: '',
        updated_at: '',
        avatar: '',
        full_avatar: '',
        single_file: {},
        ori_name: '',
        username: '',
        nickname: '',
        password: '',
        phone: '',
        email: '',
        remark: '',
        last_login_ip: '',
        last_login_time: '',
        role_ids: [],
        role_names: '',
        sorting: 100,
        status: 1
      },
      rules: {
        username: [{required: true, message: '请输入账号', trigger: 'blur'}],
        nickname: [{required: true, message: '请输入昵称', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        role_ids: [{type: 'array', required: true, validator: roleValidate, trigger: 'blur'}]
      },
      roleList: [],
      pwdDialog: false,
      pwdBtnLoading: false,
      pwdRules: {
        password: [{required: true, message: '请输入新密码', trigger: 'blur'}]
      }
    }
  },
  created() {
    this.height = screenHeight()
    this.list()
  },
  methods: {
    // 列表
    list() {
      this.loading = true
      list(this.query).then(res => {
        this.datas = res.data.data
        this.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 添加
    add() {
      this.dialogVisible = true
      this.dialogTitle = '新增'
      roleList().then(res => {
        this.roleList = res.data.data
      })
      this.reset()
    },
    // 修改
    edit(row) {
      this.dialogVisible = true
      this.dialogTitle = '编辑：' + row.id
      roleList().then(res => {
        this.roleList = res.data.data
      })
      info({
        id: row.id
      }).then(res => {
        //this.model = res.data
        let data = res.data
        data.ori_name = data.username
        data.single_file = {
          url: data.full_avatar,
          path: data.avatar
        }

        this.reset(data)
      })
    },
    // 删除
    del(row) {
      this.$confirm(
        '确定要删除ID： <span style="color:red">' + row.id + ' </span> 这条数据吗？',
        'ID：' + row.id,
        {type: 'warning', dangerouslyUseHTMLString: true}
      ).then(() => {
        this.loading = true
        del({
          id: row.id
        }).then(res => {
          this.loading = false
          if (res.status == 1) {
            this.list()
            this.reset()
            this.$message.success(res.msg)
          } else {
            this.$message.info(res.msg)
          }
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
      })
    },
    // 取消
    cancel() {
      this.reset()
      this.dialogVisible = false
    },
    // 提交
    submit() {
      this.$refs['formRef'].validate(valid => {
        if (valid) {
          if (this.model.ori_name != this.model.username) {
            this.btnLoading = true
            checkName({name: this.model.username}, 'post').then(res => {
              this.btnLoading = false
              if (res.status == 1) {
                this.$message.info('该名称已经存在！')
              } else {
                this.save()
              }
            }).catch(() => {
              this.btnLoading = false
            })
          } else {
            this.save()
          }
        }
      })
    },
    save() {
      this.btnLoading = true
      save(this.model, 'post').then(res => {
        this.btnLoading = false
        this.list()
        this.dialogVisible = false
        this.$message.success(res.msg)
      }).catch(() => {
        this.btnLoading = false
      })
    },
    // 重置
    reset(row) {
      if (row) {
        this.model = row
      } else {
        this.model = this.$options.data().model
      }
      if (this.$refs['formRef'] !== undefined) {
        this.$refs['formRef'].resetFields()
      }
    },
    // 查询
    search() {
      this.query.page = 1
      this.list()
    },
    // 刷新
    refresh() {
      this.query = this.$options.data().query
      this.list()
    },
    // 排序
    sorting(sort) {
      this.query.sort_field = sort.prop
      this.query.sort_value = ''
      if (sort.order === 'ascending') {
        this.query.sort_value = 'asc'
        this.list()
      }
      if (sort.order === 'descending') {
        this.query.sort_value = 'desc'
        this.list()
      }
    },

    // 启用/禁用
    isActivate(row) {
      this.loading = true
      disable({
        id: row.id,
        status: row.status
      }).then(res => {
        this.list()
        this.$message.success(res.msg)
      }).catch(() => {
        this.list()
      })
    },
    // 设置密码打开
    setPwd(row) {
      this.pwdDialog = true
      this.model.id = row.id
      this.model.username = row.username
      this.model.nickname = row.nickname
      this.model.password = ''
    },
    // 设置密码取消
    setPwdCancel() {
      this.pwdDialog = false
      this.reset()
    },
    // 设置密码提交
    setPwdSubmit() {
      this.$refs['pwdRef'].validate(valid => {
        if (valid) {
          this.pwdBtnLoading = true
          setPwd({
            id: this.model.id,
            password: this.model.password
          }).then(res => {
            this.pwdBtnLoading = false
            this.list()
            this.pwdDialog = false
            this.$message.success(res.msg)
          }).catch(() => {
            this.pwdBtnLoading = false
          })
        }
      })
    },

    // 文件上传回调
    singleCallback(singleFile) {
      this.model.single_file = singleFile
      this.model.avatar = singleFile.path
      this.model.full_avatar = singleFile.url
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: center;
}
.el-table .el-image {
  width: 40px;
  height: 40px;
}
</style>
